package cn.ichiva.dl4j.gnn.common;

import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class UI {

    private static Console console;
    static {
        if (GraphicsEnvironment.isHeadless()) {
            console = null;
            // 不支持
        } else {
            console = new Console();
            // 支持GUI
            console.show();
        }
    }

    private static ScheduledExecutorService executorService = null;

    public static void memory(boolean flog){
        Runtime runtime = Runtime.getRuntime();
        String mem = new StringBuffer()
                .append("可用内存[").append(runtime.maxMemory() / (1024 * 1024) + "M")
                .append("] 使用内存")
                .toString();
        if(flog){
            if(executorService == null){
                executorService = Executors.newSingleThreadScheduledExecutor();
                executorService.scheduleAtFixedRate(()->
                        put(mem,(runtime.totalMemory() - runtime.freeMemory())/(1024*1024)+"M"),
                        1,1,TimeUnit.SECONDS);
            }
        }else {
            if(null != executorService){
                executorService.shutdownNow();
                executorService = null;
            }
        }
    }

    public static void put(String k,String v){
        if(GraphicsEnvironment.isHeadless()){
            //不支持GUI输出到控制台
            log.info("{} -> {}",k,v);
        }else {
            console.put(k,v);
        }
    }

    public static void remove(String k){
        if(null != console){
            console.remove(k);
        }
    }
}
